import {replaceByObj} from "./xUtil.js";


const sizeOption=['10','20','50','100'];

const tmplBase =`
<div class="xpagination">
  <div type="total">{{total}}</div>
    <div type="select">{{select}}</div>
    <div type="page">
<ul class="pagination" type="pagination">
     {{index}}
  </ul></div>
  </div>
`;

const tmplPageIndex = `<li class="page-item {{active}}">
  <a class="page-link" {{title}} href="#" index="{{i}}">{{i}}</a>
 </li>`;

const tmplPageOption ='<option value="{{data}}" {{selected}}>{{data}} 条/页</option>';
const tmplPageSelect= '<select  class="form-select">{{option}}</select>';
const tmplTotalCount =' <span>共{{count}}条</span>';


export default  class xPagination{

    static render(cfg){
        let totalHtml ='';
        if(cfg.total)
            totalHtml = tmplTotalCount.replace('{{count}}',cfg.total);



        let optionHtml ='';
        for(let option of (cfg.sizeOption||sizeOption)){
            optionHtml += replaceByObj(tmplPageOption,{data:option,
                selected:option==cfg.pageSize?'selected':''});
        }
        let selectHtml = tmplPageSelect.replace('{{option}}',optionHtml);


        let minIndex=1;

        let maxNum =Math.ceil(cfg.total/cfg.pageSize);
        let maxIndex = maxNum;
        let pageIndex = cfg.pageIndex||1;
        if(pageIndex >maxNum)
            pageIndex = maxNum;
        //显示7个
        if(maxNum>7){
            minIndex = pageIndex-3;
            maxIndex = pageIndex+3;
            if(minIndex<1) {
                maxIndex = 7;
                minIndex = 1;
            }
            if(maxIndex>maxNum){
                maxIndex = maxNum;
                minIndex = maxNum-6;
            }
        }
        let indexHtml='';
        if(minIndex>1)
            indexHtml += replaceByObj(tmplPageIndex,{i:'&laquo;',active:'',title:'title="首页"'});
        for(let i = minIndex;i<=maxIndex; i++){
            if (i == pageIndex)
                indexHtml+=replaceByObj(tmplPageIndex,{i,active:'active',title:''});
            else
                indexHtml+=replaceByObj(tmplPageIndex,{i,active:'',title:''});
        }
        if(maxIndex<maxNum)
            indexHtml += replaceByObj(tmplPageIndex,{i:'&raquo;',active:'',title:'title="末页"'});

        return replaceByObj(tmplBase,{total:totalHtml,select:selectHtml,index:indexHtml});
    }

}

